import {
	fileUpload
} from '@/apis/uni-fetch.js';
import {
	reqGetIdCardInfo
} from "@/apis/my"
const state = {
	realInfo: {
		frontOK:false,
		backOK:false,
		// 身份证正面照
		frontUrl: '',
		// 身份证号码
		certNo: '',
		// 姓名
		name: '',
		backUrl: '',
		// 是否长期有效 1 长期 0 非长期
		certValidityType: '',
		// 结束日期
		certEndDate: '',
		// 开始日期
		certBeginDate: '',
	}
}
const mutations = {
	REAL_NAME(state, realInfo) {
		state.realInfo = {
			...state.realInfo,
			...realInfo
		};
	},
}
const actions = {
	async handlerImg(store, data) {
		let {
			type,
			tempUrl
		} = data;
		let {
			commit,
			state
		} = store;
		let fileOnlinePath = await fileUpload(tempUrl);
		uni.showLoading({
			title: '识别中...',
			mask:true
		});
		let res = await reqGetIdCardInfo({url:fileOnlinePath});
		uni.hideLoading();
		if(res.code === 200){
			// 正面
			if (type == 0) {
				if (res.data.errmsg === 'ok' && res.data.type === 'Front') {
					uni.showToast({
						title: '识别成功',
						icon: 'success'
					});
					commit('REAL_NAME', {
						certNo: res.data.id,
						name: res.data.name,
						frontUrl: fileOnlinePath,
						frontOK:true,
					})
				} else {
					commit('REAL_NAME', {
						frontUrl: fileOnlinePath,
						frontOK:false
					})
					uni.utils.toast('请上传正确的人像面');
				}
			} else {
				if (res.data.errmsg === 'ok' && res.data.type === 'Back') {
					uni.showToast({
						title: '识别成功',
						icon: 'success',
					})
					let certBeginDate = res.data.valid_date.split('-')[0];
					let certEndDate = res.data.valid_date.split('-')[1];
					let certValidityType = 0;
          certBeginDate = trimAll(certBeginDate)
					certEndDate = trimAll(certEndDate)
					if (certEndDate.length == 8 && certBeginDate.length == 8) {
						certValidityType = 0;
						console.log("非长期");
					} else if(certEndDate.length == 2 && certBeginDate.length == 8){
						console.log("长期");
						certValidityType = 1;
					} else {
						uni.utils.toast('有效期格式错误')
					};
					let backUrl = fileOnlinePath;
					commit('REAL_NAME', {
						certBeginDate,
						certEndDate,
						certValidityType,
						backUrl,
						backOK:true,
					})
				} else {
					commit('REAL_NAME', {
						backUrl: fileOnlinePath,
						backOK:false,
					})
					uni.utils.toast('请上传正确的国徽面');
				}
			}
		}else {
			uni.utils.toast('识别失败');
		}
	},
}
const getters = {
	realInfo(state) {
		return state.realInfo || {};
	}
}
export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters
}
function trimAll(ele) {
	if (typeof ele === 'string') {
		return ele.split(/[\t\r\f\n\s]*/g).join('');
	} else {
		console.error(`${typeof ele} is not the expected type, but the string type is expected`)
	}
}